<?php

namespace McUser\Model;
use Common\Model\CommonModel;

/*
 *  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

class VerifyHisModel extends CommonModel {

	protected $trueTableName = 'bg_verify_his';
	
	/*
	*	保存短信验证码
	*/
	public function save_verify_code($mobile,$ip, $verifyCode, $type){
		
		$data['mobile'] = $mobile;
		$data['ip'] = $ip;
		$data['verifyCode'] = $verifyCode;
		$data['verifyDate'] = date('Y-m-d H:i:s', time());
		$data['type'] = $type;
		
		$this -> add($data);		
	}
	

	/*
	*	检查手机号是否已经注册 ( 发送验证码是, 会检查手机是否已经注册. )
	*/
	public function check_mobile_registered($mobile){
		$where['mobile']=$mobile;
	     
	    $users_model=M("Users");
	    $result = $users_model->where($where)->count();
	    if($result){
	        return true;
	    }
	    else{
	    	return false;
	    }
	}

	/*
	*	同一个号码一天只能发送3条短信
	*/
	public function check_mobile_num($mobile){
		
		$sql = 'select * from bg_verify_his where mobile=\''.$mobile.'\' and verifyDate>\''.date('Y-m-d').'\' and verifyDate<\''.date('Y-m-d', strtotime("+1 day")).'\'';

		/*
		echo $sql."<br/>";
		*/

		/* 查找 */
		$info = $this -> query($sql) ;

		/*
		dump ($info);
		echo 'mobile count:'.count($info)."<br/>";
		*/
		
		/* 返回数据条数 */
		return count($info);
	}

	/*
	*	同一个IP每天只能发送3条短信.
	*/
	public function check_ip_num($ip){
		
		$sql = 'select count(*) as c from bg_verify_his where ip=\''.$ip.'\' and verifyDate>\''.date('Y-m-d').'\' and verifyDate<\''.date('Y-m-d', strtotime("+1 day")).'\'';

		/*
		echo $sql."<br/>";
		*/

		/* 查找 */
		$info = $this -> query($sql) ;

		/*
		dump ($info);
		echo 'ip count:'.$info['c']."<br/>";
		*/

		/* 返回数据条数 */
		return $info['c'];
	}

	/**
	 *	检查验证码是否已经失效, 是否正确等.
	 *  超过30分钟失效
	 */
	public function check_verify_code($mobile, $verifyCode, $type){

		$filter = array (
			'mobile' => $mobile,
			'verifyCode' => $verifyCode
			);

		$re = '1';

		/* 查找验证码 */
		$info = $this -> where($filter) -> find();
		
		if ($info ){
			/* 检查时间是否超过30分钟 */
			$verifyDate = $info['verifyDate'];
			$now = date('Y-m-d H:i:s', time());

			$fenZhong = ( $now - $verifyDate ) / 60; 
			if ( $fenZhong > 30 ){
				
				$re = '-103';
			}

			/*
			echo 'input verify code time:'.$fenzhong.'minites';
			*/

		}
		else{
			/*  没有找到记录 ,验证码错误 */	
			$re = '-102';
		}
		
		return $re;
	}

}